<template>
  <div class="xtx-pagination">
    <a href="javascript:;" :class="{disabled:myCurrentPage===1}" @click="changePage(myCurrentPage-1)">上一页</a>
    <span v-if="pager.start>1">...</span>
    <a href="javascript:;" :class="{active:myCurrentPage===item}" @click="changePage(item)" v-for="item in pager.arr" :key="item">{{item}}</a>
    <span v-if="pager.end<pager.pageCount">...</span>
    <a href="javascript:;" :class="{disabled:myCurrentPage===pager.pageCount}"  @click="changePage(myCurrentPage+1)">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'XtxPagination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    currentPage: {
      type: Number,
      default: 1
    },
    pageSize: {
      type: Number,
      default: 10
    }
  },
  setup (props, { emit }) {
    //   总条数
    const myTotal = ref(101)
    // 每页条数
    const myPageSize = ref(10)
    // 当前第几页
    const myCurrentPage = ref(1)
    // 按钮个数
    const btnCount = 5
    // 重点：根据上述数据得到（总页数，起始页码，结束页码，按钮数组）
    const pager = computed(() => {
      //  总页数
      const pageCount = Math.ceil(myTotal.value / myPageSize.value)
      //   起始页
      let start = myCurrentPage.value - Math.floor(btnCount / 2)
      if (start < 1) start = 1
      // 结束页
      let end = start + btnCount - 1
      if (end > pageCount) {
        end = pageCount
        start = end - btnCount + 1
        if (start < 1) start = 1
      }

      const arr = []
      for (let i = start; i <= end; i++) {
        arr.push(i)
      }
      return { pageCount, start, end, arr }
    })
    // 页码改变
    const changePage = (val) => {
      if (val < 1 || val > pager.value.pageCount || myCurrentPage.value === val) return
      myCurrentPage.value = val
      emit('current-change', val)
    }
    watch(props, () => {
      myTotal.value = props.total
      myPageSize.value = props.pageSize
      myCurrentPage.value = props.currentPage
    }, { immediate: true })
    return { pager, changePage, myCurrentPage }
  }
}
</script>
<style scoped lang="less">
.xtx-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @xtxColor;
    }
    &.active {
      background: @xtxColor;
      color: #fff;
      border-color: @xtxColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
